package com.pingxx.demo.controller;

import com.pingxx.demo.entity.User;
import com.pingxx.demo.req.UserRegisterReq;
import com.pingxx.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping("getById/{id}")
    public User getById(@PathVariable Long id) {
        return userService.getById(id);
    }

    @GetMapping("getByName")
    public User selectByName(String name) {
        return userService.getByName(name);
    }

    @PostMapping("register")
    public String register(@Valid @RequestBody UserRegisterReq req, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            StringBuffer sb = new StringBuffer();
            for (ObjectError error : bindingResult.getAllErrors()) {
                sb.append(error.getDefaultMessage()).append(",");
            }
            return sb.toString();
        }
        return "Hello Boot";
    }
}
